package com.ifacebox.client.tools;

import java.util.*;

/**
 * @author znn
 */
public class FaceImagePersonCache {
    private final Random faceImageRandom;
    private final Map<Integer, FaceImagePerson> faceImagePerson;
    private final List<Integer> faceImagePersonHashCode;

    public FaceImagePersonCache() {
        this.faceImageRandom = new Random();
        this.faceImagePerson = new HashMap<>();
        this.faceImagePersonHashCode = new ArrayList<>();
    }

    public void addFaceImagePerson(FaceImagePerson faceImagePerson) {
        this.faceImagePerson.put(faceImagePerson.hashCode(), faceImagePerson);
        this.faceImagePersonHashCode.add(faceImagePerson.hashCode());
    }

    public FaceImagePerson getRandomFaceImagePerson() {
        if (this.faceImagePerson.size() == 0) {
            return null;
        }
        int index = this.faceImageRandom.nextInt(this.faceImagePerson.size());
        return this.faceImagePerson.values().toArray(new FaceImagePerson[0])[index];
    }

    public List<FaceImagePerson> getRandomFaceImagePerson(boolean faceLuckWinRemove, int faceLuckWin) {
        if (this.faceImagePersonHashCode.size() == 0) {
            return null;
        }
        List<FaceImagePerson> faceImagePersons = new ArrayList<>(faceLuckWin);
        if (this.faceImagePersonHashCode.size() < faceLuckWin) {
            faceLuckWin = this.faceImagePersonHashCode.size();
        }
        for (int i = 0; i < faceLuckWin; i++) {
            int index = this.faceImageRandom.nextInt(this.faceImagePersonHashCode.size());
            int faceImagePersonKey = this.faceImagePersonHashCode.get(index);
            FaceImagePerson faceImagePerson = this.faceImagePerson.get(faceImagePersonKey);
            if (faceLuckWinRemove) {
                this.faceImagePerson.remove(faceImagePersonKey);
            }
            faceImagePersons.add(faceImagePerson);
            this.faceImagePersonHashCode.remove(index);
        }
        return faceImagePersons;
    }
}
